package com.ushio.capsuleservice.service.impl;

import com.ushio.capsuleservice.model.entity.*;
import com.ushio.capsuleservice.service.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class StorageService {

    @Autowired
    private ContainerService containerService;

    @Autowired
    private ArchiveService archiveService;

    @Autowired
    private PostService postService;

//    @Autowired
//    private ReplyService replyService;
//
//    @Autowired
//    private LikeService likeService;
//
//    @Autowired
//    private NotificationService notificationService;

    @Autowired
    private UserService userService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 保存数据到对应的实体表
     */
    @Transactional
    public boolean saveData(String key, String data) {
        try {
            switch (key) {
                case "time_capsule_containers":
                    return saveContainers(data);
                case "time_capsule_mind_archives":
                    return saveArchives(data);
                case "time_capsule_campfire_posts":
                    return savePosts(data);
                case "time_capsule_campfire_replies":
                    return saveReplies(data);
                case "time_capsule_campfire_user_reputation":
                    // 用户声誉可能需要特殊处理，这里简单保存
                    System.out.println("用户声誉数据: " + data);
                    return true;
                default:
                    System.err.println("未知的存储键: " + key);
                    return false;
            }
        } catch (Exception e) {
            System.err.println("保存数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 保存容器数据
     */
    private boolean saveContainers(String data) {
        try {
            log.info("保存容器数据: {}", data);
            Container container = objectMapper.readValue(data, Container.class);

            // 自动生成开始时间和结束时间
            LocalDateTime startTime = LocalDateTime.now();
            container.setStartTime(startTime);

            // TODO: 后续需要关联用户 Token
            Long userId = 1L;
            container.setUserId(userId);
            containerService.save(container);
            return true;
        } catch (Exception e) {
            System.err.println("保存容器数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 保存存档数据
     */
    private boolean saveArchives(String data) {
        try {
            List<Archive> archives = objectMapper.readValue(data, new TypeReference<List<Archive>>() {});

            // 删除用户的所有现有存档
            if (!archives.isEmpty()) {
                Long userId = archives.get(0).getUserId();
                archiveService.deleteByUserId(userId);
            }

            // 保存新存档
            archiveService.saveBatch(archives);
            return true;
        } catch (Exception e) {
            System.err.println("保存存档数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 保存帖子数据
     */
    private boolean savePosts(String data) {
        try {
            List<Post> posts = objectMapper.readValue(data, new TypeReference<List<Post>>() {});

            // 删除用户的所有现有帖子
            if (!posts.isEmpty()) {
                Long userId = posts.get(0).getUserId();
//                postService.deleteByUserId(userId);
            }

            // 保存新帖子
            postService.saveBatch(posts);
            return true;
        } catch (Exception e) {
            System.err.println("保存帖子数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 保存回复数据
     */
    private boolean saveReplies(String data) {
        try {
            List<Reply> replies = objectMapper.readValue(data, new TypeReference<List<Reply>>() {});

            // 删除用户的所有现有回复
            if (!replies.isEmpty()) {
                Long userId = replies.get(0).getUserId();
//                replyService.deleteByUserId(userId);
            }

            // 保存新回复
//            replyService.saveBatch(replies);
            return true;
        } catch (Exception e) {
            System.err.println("保存回复数据失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 从对应的实体表获取数据
     */
    public Map<String, Object> getData(String key, Long userId) {
        try {
            switch (key) {
                case "time_capsule_containers":
                    List<Container> containers = containerService.findByUserId(userId);
                    Map<String, Object> response = new HashMap<>();
                    response.put("containers", containers);
                    return response;
                case "time_capsule_mind_archives":
                    List<Archive> archives = archiveService.findByUserId(userId);
                    return Collections.singletonMap("archives", archives);
                case "time_capsule_campfire_posts":
//                    List<Post> posts = postService.findByUserId(userId);
//                    return Collections.singletonMap("posts", posts);
                case "time_capsule_campfire_replies":
//                    List<Reply> replies = replyService.findByUserId(userId);
//                    return Collections.singletonMap("replies", replies);
                case "time_capsule_campfire_user_reputation":
                    // 用户声誉可能需要特殊处理，这里返回空数组
                    return Collections.singletonMap("reputation", Collections.emptyList());
                default:
                    System.err.println("未知的存储键: " + key);
                    return null;
            }
        } catch (Exception e) {
            System.err.println("获取数据失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 从对应的实体表删除数据
     */
    @Transactional
    public boolean deleteData(String key, Long userId) {
        try {
            switch (key) {
                case "time_capsule_containers":
                    containerService.deleteByUserId(userId);
                    return true;
                case "time_capsule_mind_archives":
                    archiveService.deleteByUserId(userId);
                    return true;
                case "time_capsule_campfire_posts":
//                    postService.deleteByUserId(userId);
                    return true;
                case "time_capsule_campfire_replies":
//                    replyService.deleteByUserId(userId);
                    return true;
                case "time_capsule_campfire_user_reputation":
                    // 用户声誉可能需要特殊处理
                    return true;
                default:
                    System.err.println("未知的存储键: " + key);
                    return false;
            }
        } catch (Exception e) {
            System.err.println("删除数据失败: " + e.getMessage());
            return false;
        }
    }

}